<template>
  <el-row>
    <el-col :span="14">
      <el-upload
        class="avatar-uploader"
        :action="uploadUrl"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload">
        <el-image style="width: 100px;height: 100px;border: 1px solid #ccc"
                  :src="imgUrl"
                  fit="contain">
          <div slot="error" class="image-slot">
            <i class="el-icon-plus"></i>
          </div>
        </el-image>
      </el-upload>
    </el-col>
    <el-col :span="10">
      <el-button v-if="imgUrl" type="" icon="el-icon-delete" @click="handleDelete">删除</el-button>
    </el-col>
  </el-row>

</template>
<script>
  export default {
    props: {
      value: {
        type: String
      }
    },
    data() {
      return {
        url: this.value,
        uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload"
      }
    },
    computed: {
      imgUrl() {
        if (this.url) {
          return process.env.VUE_APP_BASE_API + '/' + this.url
        }
        return '';
      }
    },
    watch: {
      value: function (val) {
        this.url = val;
      }
    },
    methods: {
      handleDelete() {
        this.url = null;
        this.$emit('input', this.url);
      },
      handleAvatarSuccess(res, file) {
        this.url = res.fileName;
        this.$emit('input', this.url);
      },
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isLt2M;
      }
    }
  }
</script>
